package cn.conac.rc.gateway.modules.ofs.rest;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.conac.rc.framework.utils.BeanMapper;
import cn.conac.rc.framework.utils.RestClientException;
import cn.conac.rc.framework.utils.ResultPojo;
import cn.conac.rc.framework.utils.StringUtils;
import cn.conac.rc.gateway.modules.itm.service.ItemService;
import cn.conac.rc.gateway.modules.ofs.entity.OrgStatusEntity;
import cn.conac.rc.gateway.modules.ofs.entity.OrganizationBaseEntity;
import cn.conac.rc.gateway.modules.ofs.service.OrgStatusService;
import cn.conac.rc.gateway.modules.ofs.service.OrganizationBaseService;
import cn.conac.rc.gateway.modules.ofs.service.VDomainInfoService;
import cn.conac.rc.gateway.modules.ofs.vo.VDomainInfoVo;
import cn.conac.rc.gateway.security.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping(value = "ofs/")
@Api(tags = "部门的基本信息", description = "三定信息")
public class OrganizationBaseController {

    @Autowired
    OrganizationBaseService organizationBaseService;
    
    @Autowired
    VDomainInfoService vDomainInfoService;
    
    @Autowired
    OrgStatusService  orgStatusService;
	
    @Autowired
    ItemService itemService;

    @ApiOperation(value = "根据部门基本表ID取得部门基本信息", httpMethod = "GET", response = JSONObject.class, notes = "根据部门基本表ID取得部门基本信息")
    @RequestMapping(value = "bases/{id}", method = RequestMethod.GET)
    public JSONObject findDetailInfoById(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "部门基本表id", required = true) @PathVariable("id") Integer id)
            throws RestClientException, Exception {
        return organizationBaseService.findById(id);
    }
    
    @ApiOperation(value = "部门基本信息保存", httpMethod = "POST", response = JSONObject.class, notes = "部门基本信息保存")
    @RequestMapping(value = "bases/c", method = RequestMethod.POST)
    public Object cudBaseInfoSave(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "部门基本信息和状态信息的entity", required = true)  @RequestBody Map<String, Map<String, Object>> entityMap  )
            throws RestClientException, Exception {
    	
    	 ResultPojo resultInfo = new ResultPojo();
    	 Map<String,String> idMap = new HashMap<String, String>();
    	 
    	//******************第一步从页面侧获取部门基本信息和部门状态实体对象***********
         // 获得基本信息
    	 OrganizationBaseEntity baseEntityInfo = new OrganizationBaseEntity();
    	 BeanMapper.copy(entityMap.get("baseEntity"), baseEntityInfo);
    	
         // 获得部门状态信息
         OrgStatusEntity statusEntityInfo=  new OrgStatusEntity();
         BeanMapper.copy(entityMap.get("statusEntity"), statusEntityInfo);
       
         // 取得完整度掩码
         String stepMask = statusEntityInfo.getContentMask();
         // 判断是否是暂存[0]还是正常保存[1]，默认为正常保存 
         String submitType = "1";
         if(null  != stepMask ) {
        	 // 完整度掩码的格式为【111111】，当暂存场合 完整度掩码的第一个字符为[0],正常保存时为【1】
        	 submitType = stepMask.substring(0, 1);
         }
         
         //******************第二步保存部门基本信息表**************************************
         // 执行保存部门基本信息表
    	 JSONObject baseInfoJson =  organizationBaseService.saveOrUpdate(baseEntityInfo, submitType);
    	 
    	 // 判断保存是否成功失败
    	  if (ResultPojo.CODE_SUCCESS.equals(baseInfoJson.getString("code"))) {
    		  // 保存成功场合
    		  idMap.put("id", baseInfoJson.getJSONObject("result").getString("id"));
    		  resultInfo.setResult(idMap);
          } else {
        	 // 保存失败场合
        	  resultInfo.setCode(baseInfoJson.getString("code"));
        	  resultInfo.setMsg("[organizationBaseService.save] in function of baseInfoSave " 
        			  						+ ResultPojo.MSG_FAILURE  + "【" + baseInfoJson.getString("msg") + "】");
        	  resultInfo.setResult(null);
         	  return resultInfo;
          }
    	  
    	 //*******************第三步保存部门的状态表******************************************
    	 // 设置状态表ID
    	 statusEntityInfo.setId(idMap.get("id"));
    	  // 设置登录用户ID
		 statusEntityInfo.setRegUserId(UserUtils.getCurrentUser().getId());
		 statusEntityInfo.setCreateTime(new Date());
		  // 执行保存部门的状态表
		  JSONObject statusInfoJson = orgStatusService.saveOrUpdate(statusEntityInfo);
		 
		  // 判断保存是否成功失败
		  if (ResultPojo.CODE_SUCCESS.equals(statusInfoJson.getString("code")) ) {
			  // 保存成功场合
			  resultInfo.setCode(ResultPojo.CODE_SUCCESS);
			  resultInfo.setMsg(ResultPojo.MSG_SUCCESS);
		  } else {
			 // 保存失败场合
			  resultInfo.setCode(statusInfoJson.getString("code"));
			  resultInfo.setMsg("[orgStatusService.save] in function of baseInfoSave "
					  						+ ResultPojo.MSG_FAILURE + "【"  + statusInfoJson.getString("msg")  + "】");
			  resultInfo.setResult(null);
		      // 程序事务控制
		  	  // 删除保存的部门基本信息 TODO
			  return  resultInfo;
		  }
    	 
         // 成功保存部门信息表和部门状态表返回
         return  resultInfo;
    }
    
    @ApiOperation(value = "部门基本信息更新", httpMethod = "POST", response = JSONObject.class, notes = "部门基本信息更新")
    @RequestMapping(value = "bases/{baseId}/u", method = RequestMethod.POST)
    public Object cudBaseInfoUpdate(HttpServletRequest request, HttpServletResponse response,
    		@ApiParam("部门基本信息Id") @PathVariable("baseId") String baseId,
            @ApiParam(value = "部门基本信息和状态信息的entity", required = true)  @RequestBody Map<String, Map<String, Object>> entityMap  )
            throws RestClientException, Exception {
    	
    	 ResultPojo resultInfo = new ResultPojo();
    	 if(null == baseId) {
    		  // 参数baseId为null场合
	       	  resultInfo.setCode(ResultPojo.CODE_FAILURE);
	          resultInfo.setMsg("[ baseId of parameter is null ] in function of baseInfoUpdate " + ResultPojo.MSG_FAILURE);
	       	  resultInfo.setResult(null);
	       	  return resultInfo;
    	 }
    	 
    	 Map<String,String> idMap = new HashMap<String, String>();
    	 
    	//******************第一步从页面侧获取部门基本信息和部门状态实体对象***********
         // 获得基本信息
    	 OrganizationBaseEntity baseEntityInfo = new OrganizationBaseEntity();
    	 BeanMapper.copy(entityMap.get("baseEntity"), baseEntityInfo);
    	
    	 // 设置部门基本信息表baseId(确保Id不为null)
    	 baseEntityInfo.setId(baseId);
         // 获得部门状态信息
         OrgStatusEntity statusEntityInfo=  new OrgStatusEntity();
         BeanMapper.copy(entityMap.get("statusEntity"), statusEntityInfo);

         // 取得完整度掩码
         String stepMask = statusEntityInfo.getContentMask();
         // 判断是否是暂存[0]还是正常保存[1]，默认为正常保存 
         String submitType = "1";
         if(null  != stepMask ) {
        	 // 完整度掩码的格式为【111111】，当暂存场合 完整度掩码的第一个字符为[0],正常保存时为【1】
        	 submitType = stepMask.substring(0, 1);
         }
         
         //******************第二步更新部门基本信息表**************************************
         // 执行保存部门基本信息表
    	 JSONObject baseInfoJson =  organizationBaseService.saveOrUpdate(baseEntityInfo, submitType);
    	 
    	 // 判断保存是否成功失败
    	  if (ResultPojo.CODE_SUCCESS.equals(baseInfoJson.getString("code"))) {
    		  // 保存成功场合
    		  idMap.put("id", baseInfoJson.getJSONObject("result").getString("id"));
    		  resultInfo.setResult(idMap);
          } else {
        	 // 保存失败场合
        	  resultInfo.setCode(baseInfoJson.getString("code"));
        	  resultInfo.setMsg("[organizationBaseService.save] in function of baseInfoUpdate "
        			  				+ ResultPojo.MSG_FAILURE  + "【"  + baseInfoJson.getString("msg") +"】");
        	  resultInfo.setResult(null);
         	  return resultInfo;
          }
    	  
    	 //*******************第三步更新部门的状态表******************************************
    	 // 设置状态表ID
    	 statusEntityInfo.setId(idMap.get("id"));
    	 // 设置登录用户ID
		 statusEntityInfo.setUpdateUserId(UserUtils.getCurrentUser().getId());
		  // 执行保存部门的状态表
		  JSONObject statusInfoJson = orgStatusService.saveOrUpdate(statusEntityInfo);
		 
		  // 判断保存是否成功失败
		  if (ResultPojo.CODE_SUCCESS.equals(statusInfoJson.getString("code")) ) {
			  // 保存成功场合
			  resultInfo.setCode(ResultPojo.CODE_SUCCESS);
			  resultInfo.setMsg(ResultPojo.MSG_SUCCESS);
		  } else {
			 // 保存失败场合
			  resultInfo.setCode(statusInfoJson.getString("code"));
			  resultInfo.setMsg("[orgStatusService.save] in function of baseInfoUpdate " + ResultPojo.MSG_FAILURE + "【"  + statusInfoJson.getString("msg") + "】" );
			  resultInfo.setResult(null);
		      // 程序事务控制
		  	  // 删除保存的部门基本信息 TODO
			  return  resultInfo;
		  }
    	 
         // 成功保存部门信息表和部门状态表返回
         return  resultInfo;
    }

    @ApiOperation(value = "部门基本信息", notes = "组合了部门基本信息、部门网上名称信息")
    @RequestMapping(value = "bases/{id}/domains", method = RequestMethod.GET)
    public ResponseEntity<ResultPojo> getStatisticsCounts(HttpServletRequest request, HttpServletResponse response,
            @ApiParam("部门基本id") @PathVariable("id") Integer baseId) throws Exception {
        JSONObject resultJson = new JSONObject();

        // 获得基本信息
        ResultPojo result = new ResultPojo();

        JSONObject json = organizationBaseService.findById(baseId);

        result = JSONObject.toJavaObject(json, ResultPojo.class);

        if (ResultPojo.CODE_SUCCESS.equals(result.getCode())) {
            resultJson.put("baseInfo", result.getResult());
        } else {
        	result.setCode(result.getCode());
      	    result.setMsg( "部门基本信息表中以主键ID 【" + baseId  + "】的" +  result.getMsg());
            result.setResult(null);
            return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
        }
        String orgName = json.getJSONObject("result").getString("name");
        if(StringUtils.isEmpty(orgName)) {
        	  result.setCode(ResultPojo.CODE_FAILURE);
        	  result.setMsg(ResultPojo.MSG_FAILURE + " 取得的部门名称为空，不能取得对应的域名信息。");
              result.setResult(resultJson);
              return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
        }
        // 获得域名信息
        JSONObject json2 = vDomainInfoService.findByOrgName(json.getJSONObject("result").getString("name"));
        result = JSONObject.toJavaObject(json2, ResultPojo.class);
        if (ResultPojo.CODE_SUCCESS.equals(result.getCode())) {
            VDomainInfoVo domainInfo = new VDomainInfoVo();
            if (result.getResult() != null)
                resultJson.put("domainInfo", result.getResult());
            else
                resultJson.put("domainInfo", domainInfo);
        } else {
            // TODO 失败返回
        }

        // 获得部门对应权责清单数量
        JSONObject json3 = itemService.findItemsCnt(json.getJSONObject("result").getString("orgId"));
        result = JSONObject.toJavaObject(json3, ResultPojo.class);
        if (ResultPojo.CODE_SUCCESS.equals(result.getCode())) {
            resultJson.put("itemCnt", result.getResult());
        } else {
            // TODO 失败返回
        }

        result.setCode(ResultPojo.CODE_SUCCESS);
        result.setResult(resultJson);

        return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);

    }
    
    @ApiOperation(value = "根据区域ID取得待提交部门基本信息列表", httpMethod = "GET", response = JSONObject.class, notes = "根据区域ID取得待提交部门基本信息列表")
    @RequestMapping(value = "bases/{areaId}/preRealseList", method = RequestMethod.GET)
    public JSONObject findPreRealseList(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "区域ID", required = true) @PathVariable("areaId") String areaId)
            throws RestClientException, Exception {
        return organizationBaseService.preRealseList(areaId);
    }
}
